<?php

namespace app\common\service;

use app\bbs\model\BbsArticle;
use app\bbs\model\BbsUserFans;
use app\bbs\model\BbsUserView;
use app\common\enum\user\FansTypeEnum;
use app\common\model\Fans;
use app\http\exception\AuthException;
use app\user\model\User;
use app\http\exception\ApiException;
use app\user\model\UserMoney;
use randy\tools\units\ExtendQueryHelper;
use randy\tools\units\Snowflake;
use think\db\exception\DbException;
use think\facade\Db;

class UserService extends BaseService
{
    public function getUserList(ExtendQueryHelper $extendQueryHelper, $data)
    {
        $query = User::build()
                     ->with(['userMoney'])
                     ->where($extendQueryHelper->where)
                     ->order($extendQueryHelper->sort, $extendQueryHelper->order);
        $list = $extendQueryHelper->is_page ? $query->_paginate() : $query->select();
        return $list;
    }

    public function getUserItem($id)
    {
        return User::build()
                   ->findOrFail($id);
    }

    public function delUserItem($id)
    {
        $info = User::find($id);
        return $info->delete();
    }

    public function setUserItem($id, $data)
    {
        $info = User::find($id);
        $info->save($data);
        return $info;
    }


    public function addUserItem($data)
    {
        $model = new User();
        $model->save($data);
        return $model;
    }


    public static function updateFansItem(mixed $params)
    {
        $user = \app\common\model\User::build()
                                      ->find($params['user_id']);
        $user->save($params);
        return $user;
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public static function loginByOpenid($openid) : array
    {
        //获取粉丝信息
        $fans = Fans::build()
                    ->where('openid', $openid)
                    ->find();
        if (!$fans) {
            $fans_id = Snowflake::get();
            $fansData = [
                'fans_id'   => $fans_id,
                'fans_type' => FansTypeEnum::WX->value,
                'openid'    => $openid,
            ];
            Fans::build()
                ->save($fansData);
            $fans = Fans::build()
                        ->find($fans_id);
        }
        //获取用户信息
        $user = User::build()
                    ->find($fans->user_id);
        return [
            'fans'  => $fans,
            'user'  => $user,
            'token' => $user ? TokenService::setToken($user->user_id, 'app', $user->username, 'app') : ""
        ];
    }

    public static function loginById($user_id)
    {
        $user = User::build()
                    ->where('user_id', $user_id)
                    ->find();

        return [
            'user'  => $user,
            'token' => TokenService::setToken($user->user_id, 'app', $user->username, 'app')
        ];
    }

    public function disableUserItem($user_id)
    {
        $user = User::build()
                    ->find($user_id);
        if (!$user) {
            error_abort('当前用户不存在');
        }
        if ($user->status == 0) {
            error_abort(sprintf('用户%s已禁用,请勿重复禁用!', $user->nickname));
        }
        $user->status = 0;
        $user->disable_time = date('Y-m-d H:i:s');
        return $user->save();
    }

    public function unDisableUserItem($user_id)
    {
        $user = User::build()
                    ->find($user_id);
        if (!$user) {
            error_abort('当前用户不存在');
        }
        if ($user->status == 1) {
            error_abort(sprintf('用户%s未禁用 !', $user->nickname));
        }
        $user->status = 1;
        $user->disable_time = date('Y-m-d H:i:s');
        return $user->save();
    }

    public function updateNickname($nickname, $user_id)
    {
        $user = User::build()
                    ->find($user_id);
        if (!$user) {
            error_abort('当前用户不存在');
        }
        $user->nickname = $nickname;
        return $user->save();
    }

    public function updateHeadPic($head_pic, $user_id) : bool
    {
        $user = User::build()
                    ->find($user_id);
        if (!$user) {
            error_abort('当前用户不存在');
        }
        $user->head_pic = $head_pic;
        return $user->save();
    }

    public function batchDisable($user_ids) : bool
    {
        return User::build()
                   ->whereIn('user_id', $user_ids)
                   ->save(['status' => 0, 'disable_time' => date('Y-m-d H:i:s')]);
    }

    public function batchUnDisable($user_ids) : bool
    {
        return User::build()
                   ->whereIn('user_id', $user_ids)
                   ->save(['status' => 0, 'disable_time' => date('Y-m-d H:i:s')]);
    }

    /**
     * @throws DbException
     */
    public function summary($user_id) : array
    {
        $total = Db::name('view_user_total')
                   ->where('user_id', $user_id)
                   ->find();
        //发布资讯数
        $data['article_num'] = $total['article_num'] ?? 0;
        //粉丝数
        $data['fans_num'] = $total['fans_num'] ?? 0;
        // todo 关注数
        $data['follow_num'] = $total['follow_num'] ?? 0;
        $data['view_num'] = $total['view_num'] ?? 0;
        //积分余额
        $data['point'] = UserMoney::build()
                                  ->where('user_id', $user_id)
                                  ->value('points');
        return $data;
    }

    public function loginByMiniPhone($fans_id, $phone)
    {
        $fans = Fans::build()
                    ->find($fans_id);
        if (!$fans) {
            error_abort('粉丝信息不存在!');
        }
        $fans->mobile = $phone;
        $fans->save();
        if ($fans->user_id) {
            $user = $fans->user;
            $user->status == 0 && error_abort('账号已禁用, 请联系管理员!');
        } else {
            $user = new User();
            $user->username = $fans->nickname;
            $user->nickname = $fans->nickname;
            $user->mobile = $fans->mobile;
            $user->head_pic = $fans->head_pic;
            $user->status = 1;
            $user->user_type = 1;
            $user->login_time = date('Y-m-d H:i:s');
            $user->save();
            $fans->user_id = $user->user_id;
            $fans->save();
        }
        return [
            'fans'  => $fans,
            'user'  => $user,
            'token' => $user ? TokenService::setToken($user->user_id, 'app', $user->username, 'app') : ""
        ];
    }


}
